﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Web;
using Castle.MonoRail.Framework;
using Rodunu.Movies.Contracts;
using Rodunu.Movies.Interfaces.Collections;
using Rodunu.Movies.Interfaces.Movie;
using Rodunu.Movies.Interfaces.User;
using Rodunu.Movies.Logic.Collections;
using Rodunu.Movies.Logic.Movie;
using Rodunu.Movies.Logic.User;

namespace Rodunu.Movies.Web.ViewComponents
{
    public class MovieMenuComponent : ViewComponent
    {
        private readonly IUserCollections _userCollectionsLogic;
        private readonly IMovieTypes _movieTypesLogic;
        private readonly IFriends _friendsLogic;
        private readonly IUserMoviesStatus _userMoviesStatusLogic;
        private readonly ICondition _conditionLogic;

        public MovieMenuComponent()
        {
            _userCollectionsLogic = new UserCollectionsLogic();
            _movieTypesLogic = new MovieTypesLogic();
            _friendsLogic = new FriendsLogic();
            _userMoviesStatusLogic = new UserMoviesStatusLogic();
            _conditionLogic = new ConditionLogic();
        }

        public override void Render()
        {
            UserInfo user;
            if (Session == null || Session[WebConstants.USERSESSIONKEY] == null)
            {
                try
                {
                    user = (UserInfo) Thread.CurrentPrincipal;
                }
                catch (Exception ex)
                {
                    user = new UserInfo();
                    user.Id = -1;
                    user.UserName = "Guest";
                    user.IsLoggedIn = false;
                    user.IsLoaded = false;
                }
            }
            else
                user = (UserInfo)Session[WebConstants.USERSESSIONKEY];

            PropertyBag["MovieTypes"] = _movieTypesLogic.FindAll();
            PropertyBag["Friends"] = _friendsLogic.GetFriendsForUser(user.Id);
            PropertyBag["UserMoviesStatuses"] = _userMoviesStatusLogic.FindAll();
            PropertyBag["Conditions"] = _conditionLogic.FindAll();

            switch (RailsContext.CurrentController.Action)
            {
                case "AllMovies":
                    PropertyBag["AllMovies"] = "t";
                    break;
                case "UserMovies":
                    PropertyBag["AllMovies"] = "f";
                    break;
                default:
                    break;
            }
            PropertyBag["UserCollections"] = _userCollectionsLogic.GetUserCollectionsByUser(user.Id);

            base.Render();
        }
    }
}
